#!/usr/bin/env python 
# coding:utf-8
# @Time :9/11/18 15:26

import copy


class DbConfigLoader(object):
    # 最大配置的调度表数目
    __MAX_CONF_NUM = 1000

    __USED = "used"

    def __init__(self, config_table, source_db, log):
        self.log = log
        self.__config_table = config_table
        self.__source_db = source_db

    def load_conf(self):
        config_dict = {}

        try:
            for item in self.__source_db.traverse_batch(self.__config_table, {self.__USED: True}):
                table_name = item.get("_id")
                if not isinstance(table_name, str):
                    self.log.error("当前数据项_id数据类型异常: _id = {}".format(table_name))
                    continue

                result = copy.deepcopy(item)
                result.pop("_id")
                result.pop(self.__USED)
                result["table_name"] = table_name
                config_dict[table_name] = result
                if len(config_dict) >= 1000:
                    raise Exception("配置数目超出了限制...")

        except Exception as e:
            self.log.error("加载数据库中配置失败:")
            self.log.exception(e)
            return {}

        return config_dict